Home:ALL Converter>How can I use React hooks in React classic `class` component?

How can I use React hooks in React classic `class` component?

Ask Time:2018-11-19T17:09:17         Author:Aminadav Glickshtein

Json Formatter

In this example, I have this react class:

class MyDiv extends React.component
   constructor(){
      this.state={sampleState:'hello world'}
   }
   render(){
      return <div>{this.state.sampleState}
   }
}

The question is if I can add React hooks to this. I understand that React-Hooks is alternative to React Class style. But if I wish to slowly migrate into React hooks, can I add useful hooks into Classes?

Author:Aminadav Glickshtein,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/53371356/how-can-i-use-react-hooks-in-react-classic-class-component
Estus Flask :

As other answers already explain, hooks API was designed to provide function components with functionality that currently is available only in class components. Hooks aren't supposed to used in class components.\n\nClass components can be written to make easier a migration to function components.\n\nWith a single state:\n\nclass MyDiv extends Component {\n state = {sampleState: 'hello world'};\n\n render(){\n const { state } = this;\n const setState = state => this.setState(state);\n\n return <div onClick={() => setState({sampleState: 1})}>{state.sampleState}</div>;\n }\n}\n\n\nis converted to\n\nconst MyDiv = () => {\n const [state, setState] = useState({sampleState: 'hello world'});\n\n return <div onClick={() => setState({sampleState: 1})}>{state.sampleState}</div>;\n}\n\n\nNotice that useState state setter doesn't merge state properties automatically, this should be covered with setState(prevState => ({ ...prevState, foo: 1 }));\n\nWith multiple states:\n\nclass MyDiv extends Component {\n state = {sampleState: 'hello world'};\n\n render(){\n const { sampleState } = this.state;\n const setSampleState = sampleState => this.setState({ sampleState });\n\n return <div onClick={() => setSampleState(1)}>{sampleState}</div>;\n }\n}\n\n\nis converted to\n\nconst MyDiv = () => {\n const [sampleState, setSampleState] = useState('hello world');\n\n return <div onClick={() => setSampleState(1)}>{sampleState}</div>;\n}\n",
2018-11-19T09:46:52
Shubham Khatri :

Hooks are not meant to be used for classes but rather functions. If you wish to use hooks, you can start by writing new code as functional components with hooks\n\nAccording to React FAQs\n\n\n You can’t use Hooks inside of a class component, but you can\n definitely mix classes and function components with Hooks in a single\n tree. Whether a component is a class or a function that uses Hooks is\n an implementation detail of that component. In the longer term, we\n expect Hooks to be the primary way people write React components.\n\n\nconst MyDiv = () => {\n const [sampleState, setState] = useState('hello world');\n render(){\n return <div>{sampleState}</div>\n }\n}\n",
2018-11-19T09:15:44
ford04 :

Complementing Joel Cox's good answer\n\n\n\nRender Props also enable the usage of Hooks inside class components, if more flexibility is needed:\n\nclass MyDiv extends React.Component {\n render() {\n return (\n <HookWrapper\n // pass state/props from inside of MyDiv to Hook\n someProp={42} \n // process Hook return value\n render={hookValue => <div>Hello World! {hookValue}</div>} \n />\n );\n }\n}\n\nfunction HookWrapper({ someProp, render }) {\n const hookValue = useCustomHook(someProp);\n return render(hookValue);\n}\n\n\nFor side effect Hooks without return value:\n\nfunction HookWrapper({ someProp }) {\n useCustomHook(someProp);\n return null;\n}\n\n// ... usage\n<HookWrapper someProp={42} />\n\n\nSource: React Training",
2020-05-05T22:18:13
Muhammad Numan :

you can achieve this by generic High order components\nHOC\nimport React from 'react';\nconst withHook = (Component, useHook, hookName = 'hookvalue') => {\n return function WrappedComponent(props) {\n const hookValue = useHook();\n return <Component {...props} {...{[hookName]: hookValue}} />;\n };\n};\n\nexport default withHook;\n\nUsage\nclass MyComponent extends React.Component {\n render(){\n const myUseHookValue = this.props.myUseHookValue;\n return <div>{myUseHookValue}</div>;\n }\n }\n\nexport default withHook(MyComponent, useHook, 'myUseHookValue');\n",
2021-09-01T08:11:25
Venryx :

You can use the react-universal-hooks library. It lets you use the \"useXXX\" functions within the render function of class-components.\n\nIt's worked great for me so far. The only issue is that since it doesn't use the official hooks, the values don't show react-devtools.\n\nTo get around this, I created an equivalent by wrapping the hooks, and having them store their data (using object-mutation to prevent re-renders) on component.state.hookValues. (you can access the component by auto-wrapping the component render functions, to run set currentCompBeingRendered = this)\n\nFor more info on this issue (and details on the workaround), see here: https://github.com/salvoravida/react-universal-hooks/issues/7",
2019-10-25T16:23:56
Allan Duarte :

Stateful components or containers or class-based components ever support the functions of React Hooks, so we don't need to React Hooks in Stateful components just in stateless components.\n\nSome additional informations\n\nWhat are React Hooks?\nSo what are hooks? Well hooks are a new way or offer us a new way of writing our components.\n\nThus far, of course we have functional and class-based components, right? Functional components receive props and you return some JSX code that should be rendered to the screen.\n\nThey are great for presentation, so for rendering the UI part, not so much about the business logic and they are typically focused on one or a few purposes per component.\n\nClass-based components on the other hand also will receive props but they also have this internal state. Therefore class-based components are the components which actually hold the majority of our business logic, so with business logic, I mean things like we make an HTTP request and we need to handle the response and to change the internal state of the app or maybe even without HTTP. A user fills out the form and we want to show this somewhere on the screen, we need state for this, we need class-based components for this and therefore we also typically use class based components to orchestrate our other components and pass our state down as props to functional components for example.\n\nNow one problem we have with this separation, with all the benefits it adds but one problem we have is that converting from one component form to the other is annoying. It's not really difficult but it is annoying.\n\nIf you ever found yourself in a situation where you needed to convert a functional component into a class-based one, it's a lot of typing and a lot of typing of always the same things, so it's annoying.\n\nA bigger problem in quotation marks is that lifecycle hooks can be hard to use right.\n\nObviously, it's not hard to add componentDidMount and execute some code in there but knowing which lifecycle hook to use, when and how to use it correctly, that can be challenging especially in more complex applications and anyways, wouldn't it be nice if we had one way of creating components and that super component could then handle both state and side effects like HTTP requests and also render the user interface?\n\nWell, this is exactly what hooks are all about. Hooks give us a new way of creating functional components and that is important.",
2019-04-04T15:01:42
kk_360 :

React Hooks let you use react features and lifecycle without writing a class.\nIt's like the equivalent version of the class component with much smaller and readable form factor. You should migrate to React hooks because it's fun to write it.\nBut you can't write react hooks inside a class component, as it's introduced for functional component.\n\nThis can be easily converted to : \n\nclass MyDiv extends React.component\n constructor(){\n this.state={sampleState:'hello world'}\n }\n render(){\n return <div>{this.state.sampleState}\n }\n}\n\nconst MyDiv = () => {\n const [sampleState, setSampleState] = useState('hello world');\n return <div>{sampleState}</div>\n}\n",
2019-05-19T13:30:18
Aseem Upadhyay :

It won't be possible with your existing class components. You'll have to convert your class component into a functional component and then do something on the lines of - \n\nfunction MyDiv() {\nconst [sampleState, setSampleState] = useState('hello world');\nreturn (\n <div>{sampleState}</div>\n )\n}\n",
2018-11-19T09:14:59
Joel Cox :

High order components are how we have been doing this type of thing until hooks came along. You can write a simple high order component wrapper for your hook.\nfunction withMyHook(Component) {\n return function WrappedComponent(props) {\n const myHookValue = useMyHook();\n return <Component {...props} myHookValue={myHookValue} />;\n }\n}\n\nWhile this isn't truly using a hook directly from a class component, this will at least allow you to use the logic of your hook from a class component, without refactoring.\nclass MyComponent extends React.Component {\n render(){\n const myHookValue = this.props.myHookValue;\n return <div>{myHookValue}</div>;\n }\n}\n\nexport default withMyHook(MyComponent);\n",
2019-01-16T23:43:19
Fikret :

For me React.createRef() was helpful.\n\nex.:\n\nconstructor(props) {\n super(props);\n this.myRef = React.createRef();\n }\n\n...\n\n\n<FunctionComponent ref={this.myRef} />\n\n\nOrigin post here.",
2019-09-16T08:51:40
Gilad Bar :

Class components don't support hooks -\nAccording to the Hooks-FAQ:\n\nYou can’t use Hooks inside of a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component. In the longer term, we expect Hooks to be the primary way people write React components.\n",
2018-11-19T09:14:54
wisha :

I've made a library for this. React Hookable Component.\nUsage is very simple. Replace extends Component or extends PureComponent with extends HookableComponent or extends HookablePureComponent. You can then use hooks in the render() method.\nimport { HookableComponent } from 'react-hookable-component';\n\n// 👇👇👇👇👇👇👇👇\nclass ComponentThatUsesHook extends HookableComponent<Props, State> {\n render() {\n // 👇👇👇👇👇👇\n const value = useSomeHook();\n return <span>The value is {value}</span>;\n }\n}\n",
2022-02-06T07:04:50
yy